/**
 * f4tree组件，提供对象的树状选择功能 Created by lifetime on 2016/10/11.
 */
$(function() {
	if (!window.uuid) {
		window.uuid = function() {
			var s = [];
			var hexDigits = "0123456789abcdef";
			for (var i = 0; i < 36; i++) {
				s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
			}
			s[14] = "4";
			s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
			s[8] = s[13] = s[18] = s[23] = "-";
			var uuid = s.join("");
			return uuid;
		}
	}

	var htmlTemplate = "<div class='input-group f4TreeContain'>";
	htmlTemplate += "<input type='text' class='form-control showtext' style='background-color:white;' readonly value=''>";
	htmlTemplate += "<span class='input-group-addon f4TreeBtn' style='cursor:pointer;border: none;background-color: #f1f1f1;padding: 5px 8px;' ><i class='iconfont icon-chaxun' style='font-size: 20px;color: #FF008B;'></i></span>";
	htmlTemplate += "<input type='hidden' class='f4-tree-inited' title='' id='' name='' value='' />";
	htmlTemplate += "</div>";

	var treeViewTemplate = '<div class="treeView" style="display:none;position: absolute;width:280px;height:450px;background-color: white;border: 1px solid #CECECE;border-radius: 5px;z-index: 1000000;">';
	treeViewTemplate += '<span class="treeViewTitle" style="position:relative;display: block;padding: 0 10px;font-weight: bold;font-size: 17px;line-height: 40px;height: 40px;background-color: #3D95D5;color: white;">选择数据</span>';
	treeViewTemplate += '<div class="treeInstanceDiv" style="position: relative;width: 100%;height: 370px;border: none;overflow-x: hidden;overflow-y: auto;">';
	treeViewTemplate += '<ul class="ztree"></ul>';
	treeViewTemplate += '</div>';
	treeViewTemplate += '<div style="height: 40px;text-align: right;border: none;padding: 3px;">';
	treeViewTemplate += '<a class="btn btn-success">确定</a>&nbsp;&nbsp;';
	treeViewTemplate += '<a class="btn btn-cancel">取消</a>';
	treeViewTemplate += '</div>';
	treeViewTemplate += '</div>;';

	var f4treeInit = function(f4tree) {
		var newHtml = $(htmlTemplate);
		var height = f4tree.attr('data-height');
		var isMulti = f4tree.attr('data-multiSelect') == "true" ? true : false;
		if (height)
			height = parseInt(height) - 80;
		var treeValCtrl = newHtml.find('.f4-tree-inited');
		var id = f4tree.attr('id') || uuid();
		treeValCtrl.attr('id', id);
		treeValCtrl.attr('title', f4tree.attr('title') || '选择数据');
		if(f4tree.attr('name')){
			treeValCtrl.attr('name', f4tree.attr('name'));
			treeValCtrl.addClass('form-field');
		}
		treeValCtrl.attr('value', f4tree.attr('value'));
		var refTable = f4tree.attr('data-table');
		var customerUrl = f4tree.attr('customerUrl');
		treeValCtrl.attr('displayFormat', f4tree.attr('displayFormat') || 'name');
		treeValCtrl.attr('commitFormat', f4tree.attr('commitFormat') || 'id');
		f4tree.replaceWith(newHtml);
		var treeViewHtml = $(treeViewTemplate).attr('id', 'treeView-' + id);
		treeViewHtml.find('.treeViewTitle').text(treeValCtrl.attr('title'));
		treeViewHtml.data('multiSelect', isMulti);
		treeViewHtml.data('table', refTable);
		treeViewHtml.data('customerUrl', customerUrl);
		newHtml.data('treeViewHtml', treeViewHtml);
		$('body').append(treeViewHtml);
		if (height) {
			treeViewHtml.find('.treeInstanceDiv').height(height);
			treeViewHtml.css({
				"height" : height + 80
			});
		}

		var handDblclick = function(event, treeId, treeNode) {
			$('#' + id).f4tree().setValue([ treeNode ]);
			treeViewHtml.hide();
		}

		var setting = {
			view : {
				selectedMulti : false,
				showIcon : false
			},
			check : {
				enable : isMulti
			},
			data : {
				simpleData : {
					enable : true
				}
			},
			callback : {
				onDblClick : isMulti ?undefined:handDblclick ,
			},
			edit : {
				enable : false
			}
		};
		newHtml.find('.f4TreeBtn').on('click', function() {
			var view = $(this).closest('.f4TreeContain').data('treeViewHtml');
			var x = $(this).offset().left + $(this).outerWidth() - 280;
			var y = $(this).offset().top + $(this).outerHeight();
			if (!view.data("dataLoaded")) {
				var url;
				if(view.data('customerUrl')){
					url = $('body').attr('ctxPath') + (view.data('customerUrl').indexOf('/') == 0 ? view.data('customerUrl') : ('/' + view.data('customerUrl')));
				}else{
					url = $('body').attr('ctxPath') + '/f4tree/get/' + view.data('table');
				}
				$.getJSON(url, function(data) {
					var treeObj = $.fn.zTree.init(view.find(".ztree"), setting, data.data);
					view.show().offset({
						top : y,
						left : x
					});
					view.data('dataLoaded', true);
					view.data('treeObj', treeObj);
				});
			} else
				view.show().offset({
					top : y,
					left : x
				});
		});
		treeViewHtml.find('.btn-success').on('click', function() {
			var treeView = $(this).closest('.treeView');
			var isMulti = treeView.data('multiSelect');
			var treeObj = treeView.data('treeObj');
			var nodes = isMulti ? treeObj.getCheckedNodes() : treeObj.getSelectedNodes();
			var valCtrl = $('#' + treeView.attr('id').substring(9));
			if (nodes && nodes.length > 0) {
				valCtrl.f4tree().setValue(nodes);
				treeView.hide();
			} else
				alert('请选择数据');
		});
		treeViewHtml.find('.btn-cancel').on('click', function() {
			$(this).closest('.treeView').hide();
		});
		return id;
	}

	var isChange = function(arr1, arr2) {
		if (arr1 && arr2) {
			if (arr1.length != arr2.length) {
				return true;
			}
			var not;
			$(arr1).each(function(index, obj1) {
				var obj2 = arr2[index];
				for ( var key in obj1) {
					if (obj1[key] != obj2[key]) {
						not = true;
						break;
					}
				}
				if (not) {
					return false;
				}
			});
			if (not) {
				return true;
			}
			return false;
		}
		if ((arr1 && !arr2) || (!arr1 && arr2)) {
			return true;
		}
		return false;
	}

	var getObjValue = function(objs) {
		var newObjs = [];
		var excludeKeys = [ 'children', 'tId', 'parentTId', 'open', 'isParent', 'zAsync', 'isFirstNode', 'isLastNode', 'getParentNode', 'getPreNode',
				'getNextNode', 'getIndex', 'getPath', 'isAjaxing', 'checked', 'checkedOld', 'nocheck', 'chkDisabled', 'halfCheck', 'check_Child_State',
				'check_Focus', 'getCheckStatus', 'isHover', 'editNameFlag' ];
		$(objs).each(function(index, item) {
			var newo = {};
			for ( var o in item) {
				if ($.inArray(o, excludeKeys) != -1) {
					continue;
				}
				newo[o] = item[o];
			}
			newObjs.push(newo);
		});
		return newObjs;
	}

	$.fn.f4tree = function() {
		var f4tree = $(this);
		if (!f4tree.hasClass('f4-tree-inited')) {
			var id = f4treeInit(f4tree);
			f4tree = $('#' + id);
		}
		var displayInput = f4tree.prevAll('input');
		return {
			setValue : function(objs) {
				var old = f4tree.data('values');
				f4tree.data('values', objs);
				var df = f4tree.attr('displayFormat');
				var cf = f4tree.attr('commitFormat');
				var dfstr = cfstr = '';
				if($.isArray(objs)){
					$(objs).each(function(index, item) {
						if (index == objs.length - 1) {
							dfstr += item[df];
							cfstr += item[cf];
						} else {
							dfstr += (item[df] + ';');
							cfstr += (item[cf] + ';');
						}
					});
				}else{
					dfstr = objs[df];
					cfstr = objs[cf];
				}
				displayInput.val(dfstr);
				f4tree.val(cfstr);
				if (cf == '_objValue_') {
					f4tree.val(JSON.stringify(getObjValue(objs)));
				}
				if (isChange(old, objs)) {
					f4tree.trigger('valueChanged', [ old, objs ]);
				}
			},
			getValue : function() {
				return f4tree.data('values');
			}
		};
	}

	$('.f4tree').each(function() {
		var val = $(this).val();
		var ins = $(this).f4tree();
		if (val)
			ins.setValue(JSON.parse(val));
	});
	
	$(document).on('click',function(){
		if( ($(event.target).closest('.f4TreeContain').length + $(event.target).closest('.treeView').length) > 0){
			return;
		}
		$(event.target).closest('.treeView').hide();
	});
});
